package cn.hiapi.shopkeeper.service.activity;

import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.redis.service.RedisService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.config.IConfigService;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.activity.ActivityGroupBuy;
import cn.hiapi.shopkeeper.entity.order.ActivityGroupOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.jpa.activity.ActivityGroupBuyJpa;
import cn.hiapi.shopkeeper.request.CreateOrderRequest;
import cn.hiapi.shopkeeper.service.order.ActivityGroupOrderService;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author AdinZ
 * @date 2022/12/13 0:34
 */
@Service
public class ActivityGroupBuyService extends AbsActivityService<ActivityGroupBuyJpa, ActivityGroupBuy, Long> {
    public ActivityGroupBuyService(DispatchContext dispatchContext) {
        super(dispatchContext);
    }

    @Override
    public ActivityType getActivityType() {
        return ActivityType.GROUP;
    }

    @Override
    @Transactional
    public BasicEntity saveExpand(long activityId, JSONObject data) {
        if (data == null) throw new BasicException("团购数据不存在");
        ActivityGroupBuy buy = data.toJavaObject(ActivityGroupBuy.class);

        if (buy.getPrice() == null || buy.getPrice().compareTo(BigDecimal.ZERO) <= 0)
            throw new BasicException("团购价格错误");
        if (buy.getStockNum() <= 0) throw new BasicException("商品数量错误");
        if (buy.getGroupNum() <= 0) throw new BasicException("成团人数错误");


        if (StringUtils.isEmpty(buy.getTitle())) {
            throw new BasicException("商品标题错误");
        }
        buy.setAid(activityId);
        return this.save(buy);
    }

    @Override
    @Transactional
    public int deleteByAid(long aid) {
        return this.repository.deleteByAid(aid);
    }

    @Override
    @Transactional
    public ActivityOrder createOrder(BasicEntity basic, Activity activity, Map<String, Long> incrementStock, CreateOrderRequest request, Token<Object> token) {
        if (request.getOther() == null || request.getOther().isEmpty()) throw new BasicException("参数错误,other");
        String groupType = request.getOther().getString("groupType");
        if (!StringUtils.equalsAnyIgnoreCase(groupType, AppConst.GROUP_NEW, AppConst.GROUP_JOIN, AppConst.GROUP_COST)) {
            throw new BasicException("团购类型错误");
        }

        ActivityOrder order = new ActivityOrder();

        ActivityGroupBuy entity = (ActivityGroupBuy) basic;
        if (entity == null) throw new BasicException("团购活动不存在");

        //团购价格
        order.setCostPrice(activity.getPrice());
        order.setPrice(entity.getPrice());
        int stockNum = entity.getStockNum();
        long total = this.dispatchContext.getServiceOne(ProductNumService.class).totalByGid(activity.getId(), AppConst.ACTIVITY_SELL_TOTAL);
        long increment = this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 0L);
        if ((total + increment) >= stockNum) {
            throw new BasicException("已被团购光了");
        }
        this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 1L);
        incrementStock.put(AppConst.ACTIVITY_STOCK_LOCK, activity.getId());
        final ActivityGroupOrder groupOrder;
        if (StringUtils.equals(groupType, AppConst.GROUP_NEW)) {
            //新团
            groupOrder = new ActivityGroupOrder();
            groupOrder.setAid(activity.getId());
            groupOrder.setShopId(activity.getShopId());
            groupOrder.setTitle(activity.getTitle());
            groupOrder.setThumb(activity.getThumb());
            groupOrder.setPrice(entity.getPrice());
            groupOrder.setCostPrice(activity.getPrice());
            groupOrder.setGroupNum(entity.getGroupNum());
            if (entity.getTimeout() <= 0) {
                JSONObject config = this.dispatchContext.getServiceOne(IConfigService.class).getConfig(AppConst.CONFIG_SHOPKEEPER_ACTIVITY);
                int timeout = JsonUtils.getInt(config, AppConst.CONFIG_SHOPKEEPER_ACTIVITY_GROUP_TIMEOUT, 30);
                groupOrder.setTimeout(timeout);
            } else groupOrder.setTimeout(entity.getTimeout());
            groupOrder.setBuyerId(token.getFid());
            this.dispatchContext.getServiceOne(ActivityGroupOrderService.class).save(groupOrder);
        } else if (StringUtils.equalsIgnoreCase(groupType, AppConst.GROUP_JOIN)) {
            //加入别人团购
            groupOrder = this.dispatchContext.getServiceOne(ActivityGroupOrderService.class).get(request.getOther().getLongValue("gid"));
            if (groupOrder == null) throw new BasicException("加入的团购不存在");
            if (groupOrder.getStatus() != 1) throw new BasicException("加入的团购状态错误");
            if (groupOrder.getExpire() < System.currentTimeMillis()) throw new BasicException("加入的团购已超时");
            if (groupOrder.getBuyerId() == token.getFid()) throw new BasicException("不能加入自己的团购");
            long buyNum = this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, groupOrder.getId(), 0L);
            if (groupOrder.getBuyNum() + buyNum >= groupOrder.getGroupNum()) throw new BasicException("改团购已经结束");
            this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, groupOrder.getId(), 1L);
            incrementStock.put(AppConst.ACTIVITY_GROUP_STOCK_LOCK, groupOrder.getId());
        } else if (StringUtils.equalsIgnoreCase(groupType, AppConst.GROUP_COST)) {
            groupOrder = null;
            order.setCostPrice(activity.getPrice());
            order.setPrice(activity.getPrice());
        } else throw new BasicException("团购类型错误");
        if (request.getSugar() != null)
            order.setSugar(request.getSugar());
        order.setFidType(groupType);
        if (groupOrder != null) order.setFid(groupOrder.getId());
        return order;
    }

    @Override
    public BigDecimal sugarDeduction(Activity activity, BigDecimal rate, BigDecimal amount, long uid) {
        ActivityGroupBuy groupBuy = super.getByAid(activity.getId());
        return super.sugarDeduction(groupBuy.getPrice(), rate, amount);
    }


}
